package com.example.text6_server;

import android.os.Handler;
import android.text.TextUtils;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.concurrent.TimeUnit;

class UdpServer extends Thread {
    public final static int WHAT = 0x1234;
    private final static int LOCAL_PORT = 5000;

    private byte[] buffer = new byte[1024];
    private Handler handler;
    private DatagramSocket localDs;

    private boolean isStop;

    public UdpServer(Handler handler) {
        this.handler = handler;
        try {
            localDs = new DatagramSocket(LOCAL_PORT);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void onDestory() {
        isStop = true;

        if (localDs != null) {
            localDs.close();
            localDs = null;
        }
    }

    @Override
    public void run() {
        while (!isStop) {
            try {
                DatagramPacket localDp = new DatagramPacket(buffer, 1024);
                localDs.receive(localDp);
                String rec = new String(localDp.getData(), localDp.getOffset(), localDp.getLength());

                if (!TextUtils.isEmpty(rec)) {
                    handler.obtainMessage(WHAT, rec).sendToTarget();
                }

                TimeUnit.MILLISECONDS.sleep(10);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
